﻿Imports System.IO
Imports System.Reflection
Imports System.Windows.Forms
Imports System.Text
Imports System

Public Class Export_DGV_to_csv

    'Separators for CSV File
    Public Const COLUMN_Separator As String = ","
    Public Const TEXT_Separator As String = """"

    Private CSV_FileIsDefined As Boolean

    Private _Export_OK As Boolean = False
    ReadOnly Property Export_OK() As Boolean
        Get
            Return _Export_OK
        End Get
    End Property

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="dgv"></param>
    ''' <param name="FileName"></param>
    ''' <remarks></remarks>
    Sub New(dgv As DataGridView, FileName As String)
        Export(dgv, FileName, COLUMN_Separator, TEXT_Separator)
    End Sub


    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="dgv"></param>
    ''' <param name="FileName"></param>
    ''' <param name="COLUMN_Separator"></param>
    ''' <param name="TEXT_Separator"></param>
    ''' <remarks></remarks>
    Private Sub Export(dgv As DataGridView, FileName As String, COLUMN_Separator As String, TEXT_Separator As String)
        If dgv IsNot Nothing Then

            If FileName IsNot Nothing And FileName.Length > 4 Then
                If kill_old_File(FileName) Then
                    ExportDataGrid_To_CSV_File(dgv, FileName, System.Text.Encoding.UTF8, COLUMN_Separator, TEXT_Separator)
                    _Export_OK = True
                Else
                    _Export_OK = False
                End If
            End If

        Else

            If is_Language_German_Active() Then
                MessageBox.Show("Fehler: DataGrid ist leer!", "Export als CSV-Datei", MessageBoxButtons.OK)
            Else
                MessageBox.Show("Error: DataGrid is empty!", "Export as CSV-File", MessageBoxButtons.OK)
            End If

            _Export_OK = False
        End If
    End Sub



    ''' <summary>
    '''  Main-Function
    ''' </summary>
    ''' <param name="dGridView"></param>
    ''' <param name="Filename"></param>
    ''' <param name="fileEncoding"></param>
    ''' <param name="COLUMN_Separator"></param>
    ''' <param name="TEXT_Separator"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ExportDataGrid_To_CSV_File(dGridView As DataGridView, Filename As String, fileEncoding As Text.Encoding, COLUMN_Separator As String, TEXT_Separator As String) As Boolean
        Dim Created As Boolean = False
        Dim CellValue As String = String.Empty

        Try

            dGridView.EndEdit()
            dGridView.Update()

            'start StreamWriter 
            Using sw As IO.StreamWriter = New IO.StreamWriter(Filename, False, fileEncoding)

                'Create Columns
                For n As Integer = 0 To dGridView.Columns.Count - 1
                    sw.Write(TEXT_Separator)

                    If dGridView.Columns(n).HeaderText.ToString() Is Nothing Then
                        sw.Write(String.Empty)
                    Else
                        sw.Write(dGridView.Columns(n).HeaderText.ToString())
                    End If

                    If (n < dGridView.Columns.Count - 1) Then
                        sw.Write(TEXT_Separator)
                        sw.Write(COLUMN_Separator)
                    End If
                Next

                sw.Write(TEXT_Separator)
                sw.Write(sw.NewLine())

                Dim maxColCount As Integer = dGridView.Columns.Count() - 1
                For Each dgvRow As DataGridViewRow In dGridView.Rows()

                    If Not dgvRow.IsNewRow Then
                        For iColumn As Integer = 0 To maxColCount
                            sw.Write(TEXT_Separator)

                            'Item Value 
                            If dgvRow.Cells.Item(iColumn).Value IsNot Nothing Then
                                CellValue = dgvRow.Cells.Item(iColumn).Value.ToString()
                                sw.Write(CellValue)
                            Else
                                sw.Write(String.Empty)
                            End If

                            'write  <"> and <.>
                            If (iColumn < maxColCount) Then
                                sw.Write(TEXT_Separator)
                                sw.Write(COLUMN_Separator)
                            End If
                        Next
                        'write  <">
                        sw.Write(TEXT_Separator)

                        'create new Line.
                        sw.Write(sw.NewLine())
                    End If
                Next
            End Using

            ' if file created 
            If IO.File.Exists(Filename) Then
                Created = True
            End If
            Return Created
        Catch ex As IO.IOException
            MessageBox.Show(ex.Message(), "Info - IO-Exception", MessageBoxButtons.OK)
        Catch ex As Exception
            MessageBox.Show(ex.Message(), "Info - Exception", MessageBoxButtons.OK)
        End Try
        Return False
    End Function


    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="NewFileName"></param>
    ''' <param name="infoBox"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function kill_old_File(NewFileName As String, Optional infoBox As Boolean = False) As Boolean
        Try
            If File.Exists(NewFileName) Then
                File.Delete(NewFileName)
            End If

            If infoBox Then
                If is_Language_German_Active() Then
                    MessageBox.Show("Vorhandene Datei wurde gelöscht!", "Info", MessageBoxButtons.OK)
                Else
                    MessageBox.Show("Existing File now is deleted!", "Info", MessageBoxButtons.OK)
                End If
            End If

            kill_old_File = True
            Exit Function
        Catch
            If is_Language_German_Active() Then
                MessageBox.Show(NewFileName, "Die vorhandene Datei wurde nicht gelöscht!", MessageBoxButtons.OK)
            Else
                MessageBox.Show(NewFileName, "Existing File is no deleted!", MessageBoxButtons.OK)
            End If
            kill_old_File = False
        End Try
    End Function



    ''' <summary>
    ''' determine if in Windows as a language German active 
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function is_Language_German_Active() As Boolean
        Try
            Dim cultureName As String = Threading.Thread.CurrentThread.CurrentCulture.Name
            If cultureName.Substring(0, 2) = "de" Then
                is_Language_German_Active = True
            Else
                is_Language_German_Active = False
            End If
        Catch
            is_Language_German_Active = False
        End Try
    End Function

End Class
